/***************************************************************************
 创建者: 华磊
 开始时间: 2020.8.14
 copyright: (C) 华友高科
 修改说明: (每次有修改就添加一条，带有 修改人，修改时间，修改描述)
 example (1) hualei 2020.5.8 类的具体实现代码编写

 ***************************************************************************/
#include "timetool.h"
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <QCoreApplication>
#include <fcntl.h>
#include <unistd.h>


char cpuName[256];
int cpuNUM = 0;
int get_cpu_info(char* cpuName, int &cpuNUM);

static FILE *fpDebugDataFile=NULL;
#define D_TMP_DEBUG_DATA_FILE  "./debugdata.txt"
#include <QDateTime>
#define D_USE_TIMER 1

TimeTool::TimeTool(QObject *parent):
    QObject(parent)
{
    //pthread_mutexattr_init( &attr );
    //pthread_mutexattr_setprotocol( &attr, PTHREAD_PRIO_INHERIT );
    //pthread_mutex_init( &timeMutex,&attr );

    idcount=0;
    timeData.resize(D_MAX_TIME_COUNT);

    get_cpu_info(cpuName, cpuNUM);
    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    QString str = time.toString("yyyy-MM-dd--hh:mm:ss"); //设置显示格式

    // char c_date[256]=str.toLatin1().data();

#ifdef D_USE_XENOMAI
    file = QString(D_TMP_DEBUG_DATA_FILE)+"-xeno-"+str;
#elif (defined D_USE_RT_PREEMPT)
    file = QString(D_TMP_DEBUG_DATA_FILE)+"-rt-"+str;
#else
    file = QString(D_TMP_DEBUG_DATA_FILE)+"-"+str;
#endif

#if WRITE_DEBUG_DATA_FILE
    FILE* fd = fopen( file.toLatin1().data() ,"w");
    if(fd!=NULL){
        fprintf(fd,"CPU count is:%d\n",cpuNUM);
        fprintf(fd,"CPU name is:%s\n",cpuName);

#ifdef D_USE_XENOMAI
        fprintf(fd,"D_USE_XENOMAI\n");
#endif
#ifdef D_USE_RT_PREEMPT
        fprintf(fd,"D_USE_RT_PREEMPT");
#endif
#ifdef D_USE_IGH
        fprintf(fd,"D_USE_IGH \n");
#endif
#ifdef D_USE_ACONTIS
        fprintf(fd,"D_USE_ACONTIS \n");
#endif
        fclose(fd);
    }
    if ((fpDebugDataFile=fopen(file.toLatin1().data(),"a+"))==NULL)//
    {
        qDebug()<< "文件打开失败:" <<file.toLatin1().data();
    }
 # endif

#if D_USE_TIMER
    timer.start(200);
    connect(&timer, SIGNAL(timeout()), this, SLOT(slot_print()) );
#else
    connect(this, SIGNAL(signal_print(int)), this, SLOT(slot_print(int)), Qt::QueuedConnection );
#endif
}

TimeTool::~TimeTool()
{
    if(tTool)
    {
        delete tTool;
        tTool=NULL;
    }
}

int TimeTool::getTimeData(int timeIdIn, S_TIME_DATA **timeDataPointer)
{
    mutex.lock();
    if(true==timeDataMap.contains(timeIdIn))
    {
       *timeDataPointer =timeDataMap.value(timeIdIn);
        mutex.unlock();
       return 1;
    }
    else
    {
        mutex.unlock();
        return -1;
    }
}

TimeTool* TimeTool::tTool=NULL;
TimeTool* TimeTool::getInstance()
{
    if(NULL == tTool)
    {
        tTool = new TimeTool();
    }
    return tTool;
}

int TimeTool::creatTimer(QString msg,int cycle, int printInterval,
                         int min_v[3], int max_v[3], bool saveTofile)
{
    //pthread_mutex_lock(&timeMutex);
    S_TIME_DATA data;
    data.id = idcount+1;
    data.msg=msg;
    data.cycleTime=cycle;
    data.printInterval=printInterval;
    data._min[0]=min_v[0];
    data._min[1]=min_v[1];
    data._min[2]=min_v[2];
    data._max[0]=max_v[0];
    data._max[1]=max_v[1];
    data._max[2]=max_v[2];
    data.t1={0,0};
    data.t2={0,0};
    data.t3={0,0};
    data.t4={0,0};
    data.addTime=0;
    data.averageTime=0;
    data.counter=0;
    data.maxTime=0;
    data.minTime=80000000;
    data.printTime=0;
    data.maxCount[0]=0;
    data.maxCount[1]=0;
    data.maxCount[2]=0;
    data.minCount[0]=0;
    data.minCount[1]=0;
    data.minCount[2]=0;
    data.isPrintf=false;
    //   data.isPeriodTimeInitialed=false;
    data.saveToFile=saveTofile;
    timeData[idcount]=data;
    mutex.lock();
    timeDataMap.insert(data.id, &timeData[idcount]);
    mutex.unlock();

    //qDebug()<< "creat="<< data.id;
    //pthread_mutex_unlock(&timeMutex);
    idcount++;
    return data.id;
}

void TimeTool::recordInTime(int id)
{
    //pthread_mutex_lock(&timeMutex);
    S_TIME_DATA* data = timeDataMap.value(id,NULL);
    if(data)
    {
        clock_gettime(CLOCK_MONOTONIC, &data->t1);
    }else{
//        qDebug()<<"recordInTime rrrrrrrrrrrrrrrrrrrrrrrr id="<<id;
    }
    //pthread_mutex_unlock(&timeMutex);
}

void TimeTool::recordOutTime(int id)
{
    //pthread_mutex_lock(&timeMutex);
    S_TIME_DATA* data = timeDataMap.value(id,NULL);
    if(data)
    {
        if(data->t1.tv_sec==0)
        {
            //pthread_mutex_unlock(&timeMutex);
            return;
        }
        clock_gettime(CLOCK_MONOTONIC, &data->t2);
        data->nowTime=1000000000*(data->t2.tv_sec-data->t1.tv_sec)+data->t2.tv_nsec-data->t1.tv_nsec;
        //        if(data->nowTime<=0 )
        //            data->nowTime=data->cycleTime;
        data->maxTime=mymax(data->maxTime,data->nowTime);
        data->minTime=mymin(data->minTime,data->nowTime);
        data->addTime += data->nowTime;

        int t_shake=data->nowTime-data->cycleTime;//averageTime?
        if( t_shake > data->_max[2] ){
            (data->maxCount[2])++;
        }else if( t_shake > data->_max[1] ){
            (data->maxCount[1])++;
        }else if( t_shake > data->_max[0] ){
            (data->maxCount[0])++;
        }else if( t_shake < data->_min[2] ){
            (data->minCount[2])++;
        }else if( t_shake < data->_min[1] ){
            (data->minCount[1])++;
        }else if( t_shake < data->_min[0] ){
            (data->minCount[0])++;
        }

        // qDebug()<<"t_shake="<<t_shake<< data->cycleTime<<data->minTime;

        if(!data->isPrintf){
            data->counter++;
            if( data->counter > data->printInterval )
            {
                data->t4=data->t2;
                data->isPrintf=true;
#if !D_USE_TIMER
                emit signal_print(id);
                QCoreApplication::processEvents();
#endif
            }
        }
    }else{
//        qDebug()<<"recordOutTime 22rrrrrrrrrrrrrrrrrrrrrrrr id="<<id;
    }

    //pthread_mutex_unlock(&timeMutex) ;

}

void TimeTool::recordPeirodTime(int id)
{
    //pthread_mutex_lock(&timeMutex);
    S_TIME_DATA* data = timeDataMap.value(id,NULL);
    if(data)
    {
        //        if(  false == data->isPeriodTimeInitialed){
        //            data->isPeriodTimeInitialed = true;
        if( data->t1.tv_sec==0 ){
            clock_gettime(CLOCK_MONOTONIC, &data->t1);
            //pthread_mutex_unlock(&timeMutex) ;
            return;
        }
        clock_gettime(CLOCK_MONOTONIC, &data->t2);
        data->nowTime=1000000000*(data->t2.tv_sec-data->t1.tv_sec)+data->t2.tv_nsec-data->t1.tv_nsec;

        data->t1=data->t2;
        //        if(data->nowTime<=0 )
        //            data->nowTime=data->cycleTime;
        data->maxTime=mymax(data->maxTime,data->nowTime);
        data->minTime=mymin(data->minTime,data->nowTime);
        data->addTime += data->nowTime;

        int t_shake=data->nowTime-data->cycleTime;
        if( t_shake > data->_max[2] ){
            (data->maxCount[2])++;
        }else if( t_shake > data->_max[1] ){
            (data->maxCount[1])++;
        }else if( t_shake > data->_max[0] ){
            (data->maxCount[0])++;
        }else if( t_shake < data->_min[2] ){
            (data->minCount[2])++;
        }else if( t_shake < data->_min[1] ){
            (data->minCount[1])++;
        }else if( t_shake < data->_min[0] ){
            (data->minCount[0])++;
        }

        // qDebug()<<"t_shake="<<t_shake<< data->cycleTime<<data->minTime;

        if(!data->isPrintf){
            data->counter++;
            if( data->counter > data->printInterval )
            {
                data->t4=data->t2;
                data->isPrintf=true;
#if !D_USE_TIMER
                emit signal_print(id);
                QCoreApplication::processEvents();
#endif
            }
        }
    }

    //pthread_mutex_unlock(&timeMutex) ;
}

void TimeTool::slot_print()
{

#ifdef D_PRINT_TIMER_TOOL
    int len=timeDataMap.size();
    for(int i=0;i<len;i++)
    {
        slot_print(timeData[i].id);
    }
#endif

}


void TimeTool::slot_print(int id)
{
    //pthread_mutex_lock(&timeMutex);
    S_TIME_DATA* data = timeDataMap.value(id,NULL);
    if(data && data->isPrintf)
    {

        QByteArray ba;
        if(data->id==2 ){
            QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
            QString str = time.toString("yyyy-MM-dd--hh:mm:ss"); //设置显示格式
            ba = str.toLatin1();
            printf("/* -------------------------------------------------\n");
            printf("----------------------------------------------------\n");
            printf("current time : %s---------------------------------*/\n",ba.data());
        }
//        printf("%s=now:%d,min:%d,max:%d,avg:%d\t(-+10:%d,%d)(-+20:%d,%d)(-+50:%d,%d),pt:%d\n",
//               data->msg.toLatin1().data(),
//               data->nowTime/1000,
//               data->minTime/1000,
//               data->maxTime/1000,
//               data->addTime/data->counter/1000,
//               data->minCount[0],data->maxCount[0],
//                data->minCount[1],data->maxCount[1],
//                data->minCount[2],data->maxCount[2],
//                data->printTime );

        printf("%s     \t max:%d \t,avg:%d \t,min:%d \n",
               data->msg.toLatin1().data(),
               data->maxTime/1000,
               data->addTime/data->counter/1000,
               data->minTime/1000
               );

        if( data->saveToFile ){
            if ( fpDebugDataFile !=NULL )
            {
                if(data->id==2 ){
                    fprintf(fpDebugDataFile,"===================================%s\n",ba.data());
                }
                fprintf(fpDebugDataFile,"%s=now:%d,min:%d,max:%d,avg:%d\t(-+10:%d,%d)(-+20:%d,%d)(-+50:%d,%d),pt:%d\n",
                        data->msg.toLatin1().data(),
                        data->nowTime/1000,
                        data->minTime/1000,
                        data->maxTime/1000,
                        data->addTime/data->counter/1000,
                        data->minCount[0],data->maxCount[0],
                        data->minCount[1],data->maxCount[1],
                        data->minCount[2],data->maxCount[2],
                        data->printTime );

                fflush( fpDebugDataFile );
            }
        }


        data->addTime=0;
        data->counter = 0;
        data->averageTime = 0;
        data->isPrintf=false;

        clock_gettime(CLOCK_MONOTONIC,&data->t3);
        data->printTime = (data->t3.tv_nsec + 1000000000 * data->t3.tv_sec
                           - data->t4.tv_nsec - 1000000000 * data->t4.tv_sec)/1000;
    }
    //pthread_mutex_unlock(&timeMutex);
}

/**
* @brief reset　时间测量复位
*/
void TimeTool::reset(int id)
{

    //pthread_mutex_lock(&timeMutex);
    mutex.lock();
    S_TIME_DATA* data = timeDataMap.value(id,NULL);
    if(data)
    {
        data->t1={0,0};
        data->t2={0,0};
        data->t3={0,0};
        data->t4={0,0};
        data->addTime=0;
        data->averageTime=0;
        data->counter=0;
        data->maxTime=0;
        data->minTime=data->cycleTime;
        data->printTime=0;
        data->maxCount[0]=0;
        data->maxCount[1]=0;
        data->maxCount[2]=0;
        data->minCount[0]=0;
        data->minCount[1]=0;
        data->minCount[2]=0;
        data->isPrintf=false;
        //  data->isPeriodTimeInitialed=false;
    }
    mutex.unlock();
    //pthread_mutex_unlock(&timeMutex);
}

void TimeTool::resetAll()
{
    //pthread_mutex_lock(&timeMutex);
    mutex.lock();
    int len=timeData.size();
    for(int i=0;i<len;i++)
    {
        timeData[i].t1={0,0};
        timeData[i].t2={0,0};
        timeData[i].t3={0,0};
        timeData[i].t4={0,0};
        timeData[i].addTime=0;
        timeData[i].averageTime=0;
        timeData[i].counter=0;
        timeData[i].maxTime=0;
        timeData[i].minTime=80000000;//第一次传递进来的cycleTime不对
        timeData[i].printTime=0;
        timeData[i].maxCount[0]=0;
        timeData[i].maxCount[1]=0;
        timeData[i].maxCount[2]=0;
        timeData[i].minCount[0]=0;
        timeData[i].minCount[1]=0;
        timeData[i].minCount[2]=0;
        timeData[i].isPrintf=false;
        //    timeData[i].isPeriodTimeInitialed=false;

    }
    mutex.unlock();
    //pthread_mutex_unlock(&timeMutex);
}


int get_cpu_info(char* cpuName, int &cpuNUM)
{
    char cpuProce[] = "model name\t:";
    char readInfo;
    int fd = 0;
    int col = 0;
    int flag = 0;
    bool hasname=false;

    fd = open("/proc/cpuinfo", O_RDONLY);
    if (fd< 0)
    {
        return 1;
    }
    flag = 1;
    for (col = 0; read(fd, &readInfo, 1) == 1; )
    {
        if (readInfo == '\n')
        {
            col = 0;
            flag = 1;
        }
        else
        {
            if (flag && col < (sizeof(cpuProce) - 1))
            {
                if (readInfo != cpuProce[col])
                {
                    flag = 0;
                }
                col++;
            }
            else if (flag)
            {
                cpuNUM++;
                flag = 0;
                //已找到
                if( !hasname )
                {
                    for(int kk=0;  read(fd, &readInfo, 1) == 1 && kk<256 ;kk++)
                    {
                        if (readInfo != '\n')
                        {
                            cpuName[kk]=readInfo;
                        }else{
                            hasname=true;
                            break;
                        }
                    }
                }
            }
        }
    }
    printf("CPU count is:%d\n",cpuNUM);
    printf("CPU name is:%s\n",cpuName);
    close(fd);
    return 0;
}


//#if 0
/*
//而结构体timeval的定义为：
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
timezone 参数若不使用则传入NULL即可。
*/
struct timeval gettime(){
    struct timeval tv_begin ;
    gettimeofday(&tv_begin, NULL);
    return tv_begin;
}
long  gettime_second(){
    struct timeval tv_begin ;
    gettimeofday(&tv_begin, NULL);
    return tv_begin.tv_sec;
}

///======1======
static const int MON1[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};   //平年
static const int MON2[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};   //闰年
static const int FOURYEARS = (366 + 365 +365 +365); //每个四年的总天数
static const int DAYMS = 24*3600;   //每天的毫秒数

#if 0
void GetMonthAndDay(int nDays, int& nMonth, int& nDay, bool IsLeapYear)
{
    int *pMonths = IsLeapYear?MON2:MON1;
    //循环减去12个月中每个月的天数，直到剩余天数小于等于0，就找到了对应的月份
    for ( int i=0; i<12; ++i )
    {
        int nTemp = nDays - pMonths[i];
        if ( nTemp<=0 )
        {
            nMonth = i+1;
            if ( nTemp == 0 )//表示刚好是这个月的最后一天，那么天数就是这个月的总天数了
                nDay = pMonths[i];
            else
                nDay = nDays;
            break;
        }
        nDays = nTemp;
    }
}


QString gettime(){
    struct timeval tv_begin ;
    gettimeofday(&tv_begin, NULL);
    int nTime = tv_begin.tv_sec;//得到当前系统时间

    int nDays = nTime/DAYMS + 1;    //time函数获取的是从1970年以来的毫秒数，因此需要先得到天数

    int nYear4 = nDays/FOURYEARS;   //得到从1970年以来的周期（4年）的次数
    int nRemain = nDays%FOURYEARS;  //得到不足一个周期的天数
    int nDesYear = 1970 + nYear4*4;
    int nDesMonth = 0, nDesDay = 0;
    bool bLeapYear = false;

    int hour = nTime%3600;    //time函数获取的是从1970年以来的毫秒数，因此需要先得到天数
    int minute = nTime%60 ;    // 得到分钟
    int second = nTime%( DAYMS ) ;    // 得到秒


    if ( nRemain<365 )//一个周期内，第一年
    {//平年

    }
    else if ( nRemain<(365+365) )//一个周期内，第二年
    {//平年
        nDesYear += 1;
        nRemain -= 365;
    }
    else if ( nRemain<(365+365+365) )//一个周期内，第三年
    {//平年
        nDesYear += 2;
        nRemain -= (365+365);
    }
    else//一个周期内，第四年，这一年是闰年
    {//润年
        nDesYear += 3;
        nRemain -= (365+365+365);
        bLeapYear = true;
    }
    GetMonthAndDay(nRemain, nDesMonth, nDesDay, bLeapYear);


    QString strdata= QString("%1-%2-%3, %4:%5:%6").arg( nDesYear ).arg( nDesMonth ).arg( nDesMonth )
            .arg( hour ).arg( minute ).arg( second );

}

///=======2==========
bool isleapyear(int y){
    return (y % 4 == 0 && y % 100 || y % 400 == 0);
}

int sum(int y, int m, int d){
    int md[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int cnt = y * 365;
    cnt += (y - 1) / 4 + 1;
    cnt -= (y - 1) / 100 + 1;
    cnt += (y - 1) / 400 + 1;
    for(int i = 1; i < m; ++i) cnt += md[i];
    if(m > 2 && isleapyear(y)) ++cnt;
    cnt += d;
    return cnt;
}

int Count(int y1, int m1, int d1, int y2, int m2, int d2){
    return sum(y2, m2, d2) - sum(y1, m1, d1);
}

int get_now_time(){
    int y1, m1, d1, y2, m2, d2;
    while(scanf("%d%d%d%d%d%d", &y1, &m1, &d1, &y2, &m2, &d2) == 6){
        printf("%d\n", Count(y1, m1, d1, y2, m2, d2));
    }
    return 0;
}
#endif


///==========3===============
//获取总秒数 将tm结构转换为 秒数。
long rtt_mktime(S_DATE_TIME time, long timezone /*= 8*/)
{
    long res;

    // 1..12 -> 11,12,1..10, Puts Feb last since it has leap day
    if (time.month <= 2)
    {
        time.month += 10;
        time.year -= 1;
    }
    else
    {
        time.month -= 2;
    }

    /*
                // Calculate how much days from 1970 to today
                res = 59;                            //31@0001-January and 28@0001-February
                res += (time.year - 1) * 365;        //at least 365 days one year
                res += time.year / 4 - time.year / 100 + time.year / 400;    //leap years from 0001
                res += 367 * time.month / 12 - 30;    //days from March(0.5/7<=slope<0.5/5)
                res += time.day - 1;                //days
                res -= 719162;                        //days from 0001-1-1 to 1970-1-1
                // Calculate how much seconds
                res = ( (res * 24 + time.hour) * 60 + time.minute) * 60 + time.second;
    */

    res = (long)(time.year/4 - time.year/100 + time.year/400) +
            367*time.month/12 + time.day +
            time.year*365 - 719499;
    res = ((res*24 + time.hour        // now have hours
            )*60 + time.minute            // now have minutes
           )*60 + time.second;            // finally seconds

    res -= timezone * 60 * 60;
    return res;
}


//判断润年
int rtt_isleap(unsigned short year)
{
    return ((year%4==0)&&(year%100!=0)||(year%400==0));
}

//获取当地时间
void rtt_localtime( unsigned long  res, S_DATE_TIME *time,  long timezone = 8 )
{
    const int monthLengths[2][13] = {
        { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
        { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
    };
    const int yearLengths[2] = { 365, 366 };
    int year;
    int month;
    int minMonth;
    int maxMonth;

    int days;
    int clock;
    int isLeap;

    res += timezone*60*60;

    days = res / 86400;
    clock = res % 86400;
    if(clock < 0)
    {
        clock += 86400;
        days -= 1;
    }

    /**/////////////////////////////////////////////////////////////////////////////
    // Calcaulate year, 11323=0x3A4FC880/86400; 13879=0x47798280/86400
    /**////////////////////////////////////////////////////////////////////////////
    if(days >= 0)
    {
        year = days/366;
        days -= year*365 + (year+1)/4 - (year+69)/100 + (year+369)/400;

        for(time->year = year + 1970; ; time->year++)
        {
            isLeap = rtt_isleap(time->year);
            if(days < yearLengths[isLeap])
            {
                break;
            }
            days -= yearLengths[isLeap];
        }
    }
    else
    {
        year = days/366;
        days -= year*365 + (year-2)/4 - (year-30)/100 + (year-30)/400;

        for(time->year = year + 1970 - 1; ; time->year--)
        {
            isLeap = false;//rtt_isleap(time->year);
            days += yearLengths[isLeap];

            if(days >= 0)
            {
                break;
            }
        }
    }

    /**///////////////////////////////////////////////////////////////////////////
    // compute month and day, use the half search save time
    /**////////////////////////////////////////////////////////////////////////////
    minMonth = 0;
    maxMonth = 12;
    for(month = 5; month < 12 && month > 0; month = (minMonth + maxMonth) / 2)
    {
        // days between monthLengths[month]<=days<monthLengths[month+1]
        if(days < monthLengths[isLeap][month])    //too big
        {
            maxMonth = month;
        }
        else if(days >= monthLengths[isLeap][month + 1])    //too small
        {
            minMonth = month;
        }
        else    //so it is
        {
            break;
        }
    }
    days -= monthLengths[isLeap][month];
    time->month = month + 1;

    time->day = days + 1;


    /**///////////////////////////////////////////////////////////////////////////
    // Calcaulate hour minute and second
    /**///////////////////////////////////////////////////////////////////////////
    time->hour = clock / 3600;        //3600s one hour
    clock = clock % 3600;
    time->minute = clock / 60;        //60s one minute
    time->second = clock % 60;        //ms
}

static char digits[19] = {
    '9','8','7','6','5','4','3','2','1','0',
    '1','2','3','4','5','6','7','8','9'
};
int convert( char* &buf, int value){
    static const char* zero = digits + 9;//zero->'0'
    int i = value;
    char *p = buf;
    do{
        int lsd= i%10;
        i/=10;
        *p++ = zero[lsd];
    }while( i!=0 );
    if(value <0)
        *p++ = '-';
    *p = '\0';

    std::reverse(buf,p);
    return p - buf;
}
void printNowTime(   )
{
#if 1
    //测试发现localtime 获取时间太长 500us
    //    time_t timep = time(NULL);
    //    struct tm* p=localtime(&timep);//从tm结构体中可以取到年月日时分秒等值。
    //    char szTmp[50] = {0};
    //    strftime(szTmp,50,"%Y-%m-%d, %H:%M:%S",p);    //这里输出的将是 p的时间值

    //    struct timeval tv_begin ;
    //    gettimeofday(&tv_begin, NULL);
    //  rt_printf("%s /n",szTmp);

    struct timespec t1;
  //  clock_gettime(CLOCK_MONOTONIC, &t1);
    clock_gettime(CLOCK_REALTIME, &t1);
   // unsigned long long nTime = t1.tv_sec;//得到当前系统时间
    unsigned long nTime = 17500069535932;//841980/1000000;
    S_DATE_TIME dtime;
    long timezone = 8;
    rtt_localtime( nTime,  &dtime, timezone  );


    //    QString strdata = QString("zxx当前时间: %1-%2-%3, %4:%5:%6")
    //            .arg( dtime.year ).arg( dtime.month ).arg( dtime.day )
    //            .arg( dtime.hour ).arg( dtime.minute ).arg( dtime.second );
    char *szTmp = new char[100];

    //    szTmp=(char *)(strdata.toStdString().data() );
    //     sprintf( szTmp, "zxx当前时间: %d-%d-%d, %d:%d:%d"
    //                       ,dtime.year ,dtime.month , dtime.day
    //                     ,dtime.hour , dtime.minute , dtime.second );

//    char* __year=new char[ 10 ];
//    char* __month=new char[ 10 ];
//    char* __day=new char[ 10 ];
//    char* __hour=new char[ 10 ];
//    char* __minute=new char[ 10 ];
//    char* __second=new char[ 10 ];

//    convert(  __year, dtime.year );
//    convert(  __month, dtime.month );
//    convert(  __day, dtime.day );
//    convert(  __hour, dtime.hour );
//    convert(  __minute, dtime.minute );
//    convert(  __second, dtime.second );

//    strcat( szTmp, __year );
//    strcat( szTmp, __month );
//    strcat( szTmp, __day );
//    strcat( szTmp, __hour );
//    strcat( szTmp, __minute );
//    strcat( szTmp, __second );

  //  printf( "nowtime==== %s \n", szTmp );

    printf( "zxx当前时间: %d- %d-%d  %d:%d:%d\n",  dtime.year, 1, dtime.month, dtime.day,  dtime.hour, dtime.minute, dtime.second) ;
#else
    const char* test  = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toStdString().data();
    printf( "当前时间: %s\n",  test ) ;
#endif
}

/*========================================================================
* Function name        : gmt_convert_local
* Description            : 将格林尼治时间转换为本地时间
* Return type                : bool
* Argument         :
*                  : const char* gmt 格林尼治时间 20091105082121
*                  : char* local        20091105/162121
========================================================================*/
bool gmt_convert_local(const char* gmt, char* local)
{
    if ( strlen(gmt) != 14 )
        return false;
    //格林尼治时间转换为本地时间
    char year[5];
    char month[3];
    char day[3];
    char hour[3];
    char minute[3];
    char second[3];

    sscanf(gmt, "%4s%2s%2s%2s%2s%2s", year, month, day, hour, minute, second);

    S_DATE_TIME utc_time;
    S_DATE_TIME local_time;

    utc_time.year = atoi(year);
    utc_time.month = atoi(month);
    utc_time.day = atoi(day);
    utc_time.hour = atoi(hour);
    utc_time.minute = atoi(minute);
    utc_time.second = atoi(second);

    long time_second = rtt_mktime(utc_time, 0);//utc时间， 0 时区

    rtt_localtime( time_second, &local_time );

    //    sprintf(local, "%04d%02d%02d/%02d%02d%02d", local_time.year, local_time.month, local_time.day,
    //            local_time.hour, local_time.minute, local_time.second);

    return true;
}
